<template>
  <div class="auth-container">
    <div class="auth-card">
      <div class="auth-header">
        <h2>智慧农场管理系统</h2>
        <p>基于W601物联网平台</p>
      </div>

      <div class="auth-tabs">
        <div class="auth-tab" @click="$router.push('/login')">登录</div>
        <div class="auth-tab active">注册</div>
      </div>

      <div v-if="errorMessage" class="alert alert-error">{{ errorMessage }}</div>
      <div v-if="successMessage" class="alert alert-success">{{ successMessage }}</div>

      <form @submit.prevent="handleRegister">
        <div class="form-group">
          <label for="reg-username">手机号</label>
          <input
              type="text"
              id="reg-username"
              class="form-control"
              v-model="registerForm.username"
              placeholder="请输入手机号"
              :disabled="loading"
              required
          >
          <div class="field-hint">手机号将作为您的用户名</div>
        </div>

        <div class="form-group">
          <label for="reg-password">密码</label>
          <input
              type="password"
              id="reg-password"
              class="form-control"
              v-model="registerForm.password"
              placeholder="请输入密码（至少6位）"
              :disabled="loading"
              required
          >
        </div>

        <div class="form-group">
          <label for="reg-confirm-password">确认密码</label>
          <input
              type="password"
              id="reg-confirm-password"
              class="form-control"
              v-model="registerForm.confirmPassword"
              placeholder="请再次输入密码"
              :disabled="loading"
              required
          >
        </div>

        <div class="form-group">
          <label for="reg-role">角色</label>
          <select
              id="reg-role"
              class="form-control"
              v-model="registerForm.role"
              :disabled="loading"
              @change="onRoleChange"
          >
            <!-- 核心修改：option的value改为中文“用户”“管理员”，匹配后端逻辑 -->
            <option value="用户">普通用户</option>
            <option value="管理员">管理员</option>
          </select>
          <div class="field-hint">请选择您在系统中的角色</div>
        </div>

        <!-- 核心修改：普通用户手动输入管理者手机号（无需调用权限接口） -->
        <div v-if="showManagerInput" class="form-group">
          <label for="reg-manager">管理者手机号（必须填写）</label>
          <input
              type="text"
              id="reg-manager"
              class="form-control"
              v-model="registerForm.manager"
              placeholder="请输入您的管理者手机号（需是已注册的管理员）"
              :disabled="loading"
              required
              @input="clearError"
          >
          <div class="field-hint">
            管理者必须是已注册的管理员账号，若未获取请联系系统管理员
          </div>
        </div>

        <!-- 管理员身份验证（原有逻辑不变） -->
        <div v-if="showAdminVerification" class="form-group">
          <label for="admin-secret">管理员验证密钥</label>
          <input
              type="password"
              id="admin-secret"
              class="form-control"
              v-model="registerForm.adminSecret"
              placeholder="请输入管理员验证密钥"
              :disabled="loading"
              required
          >
          <div class="field-hint">注册管理员账户需要验证密钥</div>
        </div>

        <!-- 提交按钮：普通用户未填管理者时禁用 -->
        <button
            type="submit"
            class="btn"
            :disabled="loading || (showManagerInput && !registerForm.manager)"
            :class="{ 'btn-loading': loading }"
        >
          {{ loading ? '注册中...' : '注册' }}
        </button>
      </form>

      <div class="login-link">
        已有账号？<span @click="$router.push('/login')">立即登录</span>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { userAPI } from '@/api/userAPI'

export default {
  name: 'Register',
  setup() {
    const router = useRouter()

    // 表单数据：新增manager字段（手动输入）
    const registerForm = ref({
      username: '',
      password: '',
      confirmPassword: '',
      role: '用户', // 默认值改为中文“用户”，匹配option的value
      adminSecret: '',
      manager: '' // 管理者手机号（手动输入）
    })

    const errorMessage = ref('')
    const successMessage = ref('')
    const loading = ref(false)

    // 计算属性：仅普通用户显示管理者输入框（改为匹配中文“用户”）
    const showManagerInput = computed(() => {
      return registerForm.value.role === '用户'
    })

    // 计算属性：管理员注册时显示密钥验证（改为匹配中文“管理员”）
    const showAdminVerification = computed(() => {
      return registerForm.value.role === '管理员'
    })

    // 角色切换时清空关联字段
    const onRoleChange = () => {
      registerForm.value.adminSecret = ''
      registerForm.value.manager = ''
      clearError()
    }

    // 表单验证（适配手动输入场景）
    const validateForm = () => {
      errorMessage.value = ''
      successMessage.value = ''

      // 1. 手机号格式验证（自身手机号 + 管理者手机号）
      const phoneRegex = /^1[3-9]\d{9}$/
      if (!phoneRegex.test(registerForm.value.username)) {
        errorMessage.value = '请输入正确的手机号格式'
        return false
      }

      // 2. 普通用户：管理者手机号格式验证
      if (showManagerInput.value) {
        if (!phoneRegex.test(registerForm.value.manager)) {
          errorMessage.value = '请输入正确的管理者手机号格式'
          return false
        }
        // 禁止自己作为自己的管理者
        if (registerForm.value.manager === registerForm.value.username) {
          errorMessage.value = '不能选择自己作为管理者'
          return false
        }
      }

      // 3. 密码验证（原有逻辑不变）
      if (registerForm.value.password.length < 6) {
        errorMessage.value = '密码长度不能少于6位'
        return false
      }
      if (registerForm.value.password !== registerForm.value.confirmPassword) {
        errorMessage.value = '两次输入的密码不一致'
        return false
      }

      // 4. 管理员密钥验证（原有逻辑不变）
      if (showAdminVerification.value) {
        if (!registerForm.value.adminSecret) {
          errorMessage.value = '请输入管理员验证密钥'
          return false
        }
        if (registerForm.value.adminSecret !== '123456') {
          errorMessage.value = '管理员验证密钥错误'
          return false
        }
      }

      return true
    }

    // 注册提交（核心：传递manager字段给后端）
    const handleRegister = async () => {
      if (!validateForm()) return

      loading.value = true
      try {
        // 构造请求数据：包含manager字段（后端已支持接收）
        const requestData = {
          phone: registerForm.value.username, // 注册者手机号
          password: registerForm.value.password, // 密码
          role: registerForm.value.role, // 角色（现在是“用户”或“管理员”，匹配后端逻辑）
          manager: registerForm.value.manager // 管理者手机号（普通用户必填）
        }

        console.log('注册请求数据（含管理者）:', requestData)
        const result = await userAPI.register(requestData)

        // 后端返回结果处理（后端会校验管理者是否存在、是否为管理员）
        if (result.success) {
          successMessage.value = '注册成功！2秒后自动跳转到登录页面'
          // 清空表单
          registerForm.value = {
            username: '',
            password: '',
            confirmPassword: '',
            role: '用户', // 重置为中文默认值
            adminSecret: '',
            manager: ''
          }
          // 2秒后跳转登录页
          setTimeout(() => {
            router.push('/login')
          }, 2000)
        } else {
          // 后端返回的错误信息（如“管理者不存在”“管理者不是管理员”等）
          errorMessage.value = result.message || '注册失败，请重试'
        }
      } catch (error) {
        console.error('注册异常:', error)
        // 网络错误或后端未返回明确信息时的提示
        errorMessage.value = error.response?.data?.message || '注册失败，请检查网络或联系管理员'
      } finally {
        loading.value = false
      }
    }

    // 清除错误信息
    const clearError = () => {
      if (errorMessage.value) {
        errorMessage.value = ''
      }
    }

    return {
      registerForm,
      errorMessage,
      successMessage,
      loading,
      showManagerInput,
      showAdminVerification,
      onRoleChange,
      handleRegister,
      clearError
    }
  }
}
</script>

<style scoped>
/* 原有样式不变，无需修改 */
.auth-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #2d5a27 0%, #48bb78 100%);
  padding: 20px;
}

.auth-card {
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
  padding: 30px;
}

.auth-header {
  text-align: center;
  margin-bottom: 25px;
}

.auth-header h2 {
  color: #2d5a27;
  margin-bottom: 10px;
  font-size: 1.5rem;
}

.auth-header p {
  color: #718096;
  font-size: 0.9rem;
}

.auth-tabs {
  display: flex;
  margin-bottom: 20px;
  border-bottom: 1px solid #e2e8f0;
}

.auth-tab {
  flex: 1;
  text-align: center;
  padding: 12px;
  cursor: pointer;
  transition: all 0.3s;
  color: #718096;
  font-weight: 500;
}

.auth-tab.active {
  border-bottom: 3px solid #48bb78;
  color: #2d5a27;
  font-weight: 600;
}

.auth-tab:not(.active):hover {
  color: #4a5568;
  background-color: #f7fafc;
}

.form-group {
  margin-bottom: 20px;
  position: relative;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #4a5568;
}

.form-control {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #cbd5e0;
  border-radius: 5px;
  font-size: 16px;
  transition: all 0.3s;
  box-sizing: border-box;
}

.form-control:focus {
  border-color: #48bb78;
  outline: none;
  box-shadow: 0 0 0 3px rgba(72, 187, 120, 0.1);
}

.form-control:disabled {
  background-color: #f7fafc;
  cursor: not-allowed;
  opacity: 0.7;
}

select.form-control {
  appearance: none;
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e");
  background-position: right 0.5rem center;
  background-repeat: no-repeat;
  background-size: 1.5em 1.5em;
  padding-right: 2.5rem;
}

.field-hint {
  font-size: 0.75rem;
  color: #718096;
  margin-top: 5px;
}

.btn {
  width: 100%;
  padding: 12px;
  background: linear-gradient(135deg, #48bb78, #2d5a27);
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
  margin-top: 10px;
}

.btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(72, 187, 120, 0.4);
}

.btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.btn-loading {
  color: transparent;
}

.btn-loading::after {
  content: '';
  position: absolute;
  width: 20px;
  height: 20px;
  top: 50%;
  left: 50%;
  margin-left: -10px;
  margin-top: -10px;
  border: 2px solid #ffffff;
  border-radius: 50%;
  border-top-color: transparent;
  animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.alert {
  padding: 12px;
  border-radius: 5px;
  margin-bottom: 20px;
  text-align: center;
  font-size: 14px;
}

.alert-error {
  background-color: #fed7d7;
  color: #c53030;
  border: 1px solid #feb2b2;
}

.alert-success {
  background-color: #c6f6d5;
  color: #276749;
  border: 1px solid #9ae6b4;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
  color: #718096;
}

.login-link span {
  color: #48bb78;
  cursor: pointer;
  font-weight: 500;
  text-decoration: underline;
}

.login-link span:hover {
  color: #2d5a27;
}
</style>